/**
 *
 */
package com.wedroid.r2d2.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * @author lute
 */
public class XmlStringUtils {

    /**
     * Find XML element of specific content
     * @param element
     * @param content
     * @return
     */
    public static String findElement(String element, String content) {
        String regex = new StringBuffer("<").append(element)
                                            .append(">(.*?)</")
                                            .append(element)
                                            .append(">")
                                            .toString();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        String result = findMatcherGroup(matcher, 1);
        if (result.startsWith("<![CDATA[") && result.endsWith("]]>")) {
            return StringUtils.substring(result, 9, -3);
        } else {
            return result;
        }
    }

    /**
     * Find XML attribute of specific content
     * @param key
     * @param content
     * @return
     */
    public static String findAttribute(String key, String content) {
        Pattern pattern = Pattern.compile(key + "\\s?=\\s?\"([^\"<]+)\"");
        Matcher matcher = pattern.matcher(content);
        return findMatcherGroup(matcher, 1);
    }

    /**
     * @param matcher
     * @param group
     * @return
     */
    private static String findMatcherGroup(Matcher matcher, int group) {
        if (matcher.find()) {
            String match = matcher.group(group);
            if (StringUtils.isNotBlank(match)) {
                return match;
            }
        }
        return "";
    }

}
